package servlet;

import dao.MusicDao;
import entity.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.Date;

@WebServlet("/upload")
@MultipartConfig
//上传音乐
public class UpLoadMusicServlet extends HttpServlet {
    private static final String SAVEPATH =
            "D:\\项目\\music\\src\\main\\webapp\\music\\";
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html; charset=utf-8");
        User user = (User) req.getSession().getAttribute("user");
        if (user == null){
            System.out.println("没有登录，不能上传！");
        }else {
            //先上传服务器
            //part类避免文件重复上传
            Part part = req.getPart("filename");
            //分别获取相应的信息存入服务器，title，singer，time,url,userId
            //从content-disposition头中获取源文件名
            String header = part.getHeader("Content-Disposition");
            int start = header.lastIndexOf("=");
            String fileName = header.substring(start+1).
                    replace("\"","");
            System.out.println("filename:"+fileName);
            //谷歌浏览器会自动解析 postman测试需要处理，
            // 之后只能识别汉字，其他类型命名上传会出现失败
            int index = fileName.indexOf("%");
            fileName = fileName.substring(index);
            //对音乐名解码
            fileName = URLDecoder.decode(fileName,"utf-8");
            part.write(SAVEPATH+ fileName);
            System.out.println("filename2:"+fileName);
            //获取歌手名
            String singer = req.getParameter("singer");
            System.out.println("歌手："+singer);

            //2、插入数据库
            String[] titles = fileName.split("\\.");
            String title = titles[0];
            System.out.println("title:" + title);
            String url = "music\\"+title;
            System.out.println("url："+url);
            SimpleDateFormat simpleDateFormat =
                    new SimpleDateFormat("yyyy-MM-dd");
            //大写MM表示月份，小写mm代表分钟
            String time = simpleDateFormat.format(new Date());
            int userId = user.getId();
            MusicDao musicDao = new MusicDao();
            int ret = musicDao.insert(title,singer,time,url,userId);
            if (ret == 1){
                //System.out.println("上传成功！");
                resp.sendRedirect("list.html");
            }else {
                System.out.println("上传失败");
                part.delete();
            }
        }
    }
}
